package com.dmall.graph.bfs;

import com.dmall.graph.Graph;

import java.util.LinkedList;
import java.util.Queue;

public class BipartitionDetection {

    private Graph G;
    private boolean[] visited;
    private int[] colors;
    private boolean isBipartite = true;

    public BipartitionDetection(Graph G) {
        this.G = G;
        visited = new boolean[G.V()];
        colors = new int[G.V()];
        for (int i = 0; i < G.V(); i++) {
            colors[i] = -1;
        }
        for (int v = 0; v < G.V(); v++) {
            if (!visited[v]) {
                if (!bfs(v)) {
                    isBipartite = false;
                    break;
                }
            }
        }
    }

    private boolean bfs(int s) {
        Queue<Integer> queue = new LinkedList<>();
        queue.add(s);
        visited[s] = true;
        colors[s] = 0;
        while (!queue.isEmpty()) {
            Integer v = queue.remove();
            for (Integer w : G.adj(v)) {
                if (!visited[w]) {
                    queue.add(w);
                    visited[w] = true;
                    colors[w] = 1 - colors[v];
                } else if (colors[w] == colors[v]) {
                    return false;
                }
            }
        }
        return true;
    }

    public boolean isBipartite(){
        return isBipartite;
    }

    public static void main(String[] args) {
        String filename = BipartitionDetection.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        BipartitionDetection biPartitionDetection = new BipartitionDetection(g);
        System.out.println(biPartitionDetection.isBipartite());

        String filename2 = BipartitionDetection.class.getClassLoader().getResource("g3.txt").getPath();
        Graph g2 = new Graph(filename2);
        BipartitionDetection biPartitionDetection2 = new BipartitionDetection(g2);
        System.out.println(biPartitionDetection2.isBipartite());
    }
}
